
PROJECT_NAME := $(shell grep -E '^name' Cargo.toml | sed -E 's/name = "(.*)"/\1/' | head -1)
PROJECT_VERSION := $(shell grep -E '^version' Cargo.toml | sed -E 's/version = "(.*)"/\1/' | head -1)
WORKSPACE_DIR := ${PWD}
TARGET_DIR := ${WORKSPACE_DIR}/target
REPO_URL := $(shell git remote get-url origin 2>/dev/null | sed 's/\.git$$//')
FILES := $(shell find $(PWD) -type f -not -path '*/\.*/*' -not -name '.*' 2>/dev/null)
TEMPLATE_REPO_URL := https://gitee\.com/helloworld/rust-template

ifneq ($(shell git rev-parse --is-inside-work-tree 2>/dev/null),true)
COMMIT_TAG := unknown
else
COMMIT_TAG := $(shell git rev-parse --short=8 HEAD)
endif

#############################
# install tool if not exist
# $(1): tool name
# $(2): tool-cli
# $(3): install tool command
#############################
define install_tool_if_not_exist
@if command -v $(2) 1>/dev/null; then \
	printf "\033[32m[√]\033[0m$(1) has been installed\n"; \
else \
	printf "\033[33m[×]\033[0m$(1) has not been installed, install now...\n"; \
	$(3); \
fi
endef


help: Makefile	## show makefile usage
	@echo "========================="
	@echo "project name: ${PROJECT_NAME}"
	@echo "project version: ${PROJECT_VERSION}"
	@echo "commit tag: ${COMMIT_TAG}"
	@echo "git repo url: ${REPO_URL}"
	@echo "========================="
	@grep -E '^[a-zA-Z_-]+:.*?## .*$$' Makefile | awk 'BEGIN {FS = ":.*?## "}; {printf "\033[36m%-30s\033[0m %s\n", $$1, $$2}'

.PHONY: clean
clean:	## clean generated files
	rm -rf ${TARGET_DIR}

.PHONY: format
format: ## format sources
	cargo fmt

.PHONY: update-repo-info
update-repo-info: $(FILES)	## update repo info of git
	$(if $(REPO_URL),,\
		$(error 'git remote get-url origin' returned empty))
	@$(foreach f,$(FILES),\
		sed -i 's|$(TEMPLATE_REPO_URL)|$(REPO_URL)|g' $(f);)
	@echo "Done: replaced $(TEMPLATE_REPO_URL) -> $(REPO_URL)"

.PHONY: prepare-dev
prepare-dev: ## prepare pre commit environment, which will install tools
	$(call install_tool_if_not_exist, pipx, pipx, pipx install pre-commit)
	$(call install_tool_if_not_exist, cargo-generate, cargo-generate, cargo install cargo-generate)
	$(call install_tool_if_not_exist, cargo-deny, cargo-deny, cargo install --locked cargo-deny)
	$(call install_tool_if_not_exist, typos-cli, typos, cargo install typos-cli)
	$(call install_tool_if_not_exist, git-cliff, git-cliff, cargo install git-cliff)
	$(call install_tool_if_not_exist, cargo-nextest, cargo-nextest, cargo install cargo-nextest --locked)
	@echo ''
	@echo '#################################'
	@echo 'Note:'
	@echo '- execute "pre-commit install" to init current repo if init this repo first time.'
	@echo '- execute "cargo deny fetch" to get database if install cargo-deny first time.'
	@echo '- execute "make update-repo-info" to use git origin replace demo repo url after init template and create remote repo.'
	@echo '#################################'
	@echo ''
